/*
 * @Describe: 适用于 sessionStorage 存储解决方案(存储加密和获取解密)
 * @Author:
 * @Date:
 * @LastEditTime:
 * @FilePath:
 */
import CryptoJS from "crypto-js";

const aseKey = "**_ZSfw_AMIS_KEY"; // 秘钥必须为：8/16/32位
const KEY = "KEY_EXTRA";

/**
 * 加密存储临时数据并解析对象
 */
export default class ACrypto {
  // 加密
  static setSS(value: any, key?: string) {
    if (key) {
      const stringify = JSON.stringify(value);
      const encrypt = CryptoJS.AES.encrypt(stringify, CryptoJS.enc.Utf8.parse(aseKey), {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      }).toString();
      window.sessionStorage.setItem(key, encrypt);
      return encrypt;
    } else {
      const encrypt = CryptoJS.AES.encrypt(value, CryptoJS.enc.Utf8.parse(aseKey), {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      }).toString();
      if (key) {
        window.sessionStorage.setItem(key, encrypt);
      }
      return encrypt;
    }
  }
  // 解密
  static getSS(value: string, key?: string) {
    if (key) {
      const ssStr = window.sessionStorage.getItem(key) || "";
      try {
        if (ssStr) {
          const decrypt = CryptoJS.AES.decrypt(ssStr, CryptoJS.enc.Utf8.parse(aseKey), {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
          }).toString(CryptoJS.enc.Utf8);
          const parseStr = JSON.parse(decrypt);
          return parseStr;
        }
        return value;
      } catch (e) {
        return value;
      }
    } else {
      try {
        if (value) {
          const decrypt = CryptoJS.AES.decrypt(value, CryptoJS.enc.Utf8.parse(aseKey), {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
          }).toString(CryptoJS.enc.Utf8);
          return decrypt === "" ? value : decrypt;
        } else {
        }
        return value;
      } catch (e) {
        return value;
      }
    }
  }
  // 删除key
  static removeSS(key = KEY) {
    window.sessionStorage.removeItem(key);
  }
  // 清除所有session
  static clearSS(key = KEY) {
    window.sessionStorage.clear();
  }
}
